package com.psak.cudaphrasal.server.service.task;

import java.util.List;

import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;

import com.psak.cudaphrasal.model.FileChunkToProcess;
import com.psak.cudaphrasal.server.service.cache.ResultsCache;

/**
 * Usluga zajmuje sie rodzieleniem zadan pomiedzy node'y.
 * 
 * @author piotrs10
 * 
 */
public class TaskDispatcherService {
	private ResultsCache resultsCache;
	private JmsTemplate jmsTemplate;
	private String sendQueueName;

	/**
	 * Metoda rozdziela zadania do node'ow poprzez kolejke.
	 * 
	 * @param taskChunks
	 *            Fragmenty pliku stanowiace zadania do przetwarzania dla
	 *            node'ow.
	 * @throws TaskDispatcherServiceException
	 */
	public void dispatchTasks(List<FileChunkToProcess> taskChunks)
			throws TaskDispatcherServiceException {
		for (FileChunkToProcess chunk : taskChunks) {
			try {
				jmsTemplate.send(sendQueueName, new TaskMessageBuilder(chunk));
			} catch (JmsException e) {
				throw new TaskDispatcherServiceException(
						"Blad podczas wysylania wiadaomosci do kolejki", e);
			}
		}
		resultsCache.setNumberOfAllResults(taskChunks.size());
	}

	public void setJmsTemplate(JmsTemplate jmsTemplate) {
		this.jmsTemplate = jmsTemplate;
	}

	public void setSendQueueName(String sendQueueName) {
		this.sendQueueName = sendQueueName;
	}

	public void setResultsCache(ResultsCache resultsCache) {
		this.resultsCache = resultsCache;
	}

}
